$(document).ready(function () {
    formValidInit();
    tableInit();
    fileUpload();
    ueditorInit();
});

function setCount(data, id) {
    $('#number-' + id).text($(data).text());
    var count = parseInt($(data).text()) * parseInt($("#countValid-" + id).val());
    $('#count-' + id).val(count);
}

function getCount(data, id) {
    var count = parseInt($(data).val()) * parseInt($('#number-' + id).text());
    $('#count-' + id).val(count);
}

function editGoods(id, name, price, index,describe,images) {
    formInit();
    $('input[name="id"]').val(id);
    $('input[name="name"]').val(name);
    $('input[name="price"]').val(price);
    $('input[name="files"]').val(images)
    var length = $('#data-' + index + ' input').length;
    UE.getEditor('editor').setContent(describe);
    for (var i = 0; i < length; i++) {
        if(i != 0){
            addNode(i);
        }
        var data = $('#data-' + index + ' input').eq(i).val().split(',');
        $('#info-' + i + " input[name='size']").val(data[1]);
        $('#count-' + i).val(data[0]);
        $('#countValid-' + i).val(data[0]);
    }
}

function updateGoods(page) {
    $('input[name="number"]').val($('#info .input-group').length);
    postAjax('/goods/updateGoods', $('#addGoods').serialize(), function (data) {
        if (data.status == 200) {
            showAlert(data.message, function () {
                $('#myModal').modal('hide');
                location.reload(false)
            })
        }
    })
}

function saveGoods() {
    $('input[name="number"]').val($('#info .input-group').length);
    $('#addGoods').data('formValidation').validate();
    if ($('#addGoods').data('formValidation').isValid()) {
        postAjax('/goods/addGoods', $('#addGoods').serialize(), function (data) {
            if (data.status == 200) {
                showAlert(data.message, function () {
                    jumpPage('/goods/addGoods');
                })
            } else {
                showAlert(data.message);
            }
        }, function () {
            showAlert('服务器出错')
        })
    }
}

function delGoods(id) {
    showConfirm('你确定删除该商品吗？', function () {
        getAjax('/goods/delGoods?id=' + id, function (data) {
            if (data.status == 200) {
                showAlert(data.message, function () {
                    jumpPage('/goods/getShopkeeperGoods');
                })
            }
        })
    })
}

function formValidInit() {
    $('#addGoods')
        .formValidation({
            message: '输入的值无效',
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                name: {
                    validators: {
                        notEmpty: {
                            message: '商品名不能为空'
                        }
                    }
                },
                countValid: {
                    validators: {
                        notEmpty: {
                            message: '数量不能为空'
                        },
                        between: {
                            min: 1,
                            max: 100000000,
                            message: '输入值非负值或者是零'
                        }
                    }
                },
                price: {
                    validators: {
                        notEmpty: {
                            message: '商品价格不能为空'
                        },
                        between: {
                            min: 1,
                            max: 100000000,
                            message: '输入值非负值或者是零'
                        }
                    }
                },
                size: {
                    validators: {
                        notEmpty: {
                            message: '商品大小不能为空,如没有商品大小请设置成“无”'
                        }
                    }
                }
            }
        })
}

function formInit() {
    $('input[read="true"]').attr('readonly', true);
    $('#addGoods').append('<input type="text" name="id" class="hide">');
    $('form > div > button').attr('onclick', "updateGoods()");
    $('form > div > button').text("修改商品");
}

function tableInit() {
    if ($("#goodsName").text().length > 35) {
        $("#goodsName").text(($("#goodsName").text()).slice(0, 35) + '...');
    }
}

function fileUpload() {
    $('#file').fileinput({
        uploadUrl: '/goods/upload',
        uploadAsync: false,
        showBrowse: false,
        maxFileCount: 6,
        minFileCount: 1,
        validateInitialCount: true,
        maxImageHeight: 400,
        maxImageWidth: 400,
        resizeImage: true,
        browseOnZoneClick: true
    });
    $('#file').on('filebatchuploadsuccess', function (event, data, previewId, index) {
        var filePath = [];
        console.log(data.response.data)
        for (var i in data.response.data) {
            filePath.push(data.response.data[i].path)
        }
        $('input[name="files"]').val(filePath);
    });
}

function ueditorInit() {
    UE.getEditor('editor');
}

function search(min, max, data) {
    var count = parseInt($(data).val());
    if (count > parseInt(max)) {
        count = parseInt(max);
    } else if (count < parseInt(min)) {
        count = parseInt(min);
    }
    jumpPage('/goods/getShopkeeperGoods?page=' + count);
}

function addNode(length) {
    var id = length || $('#info .input-group').length;
    $('#info').append(
        '<div id="info-' + id + '">' +
        '<div class="input-group" id="info-0">' +
        '<div class="input-group-btn">' +
        '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">' +
        '选择数量' +
        '<span class="caret"></span>' +
        '</button>' +
        '<ul class="dropdown-menu pull-right">' +
        '<li><a href="javascript:;" onclick="setCount(this,' + "'" + id + "'" + ')">100</a>' +
        '</li>' +
        '<li><a href="javascript:;" onclick="setCount(this,' + "'" + id + "'" + ')">1000</a></li> ' +
        '<li><a href="javascript:;" onclick="setCount(this,' + "'" + id + "'" + ')">10000</a></li>' +
        '</ul></div>' +
        '<input class="form-control" type="text" name="size" placeholder="商品大小" style="width: 50%;float: left;padding: 5px"/>' +
        '<input class="form-control" type="text" placeholder="请输入数量" id="countValid-' + id + '" name="countValid" onchange="getCount(this,' + "'" + id + "'" + ')" style="width: 50%;float: left;padding: 5px"/> ' +
        '<span class="input-group-addon" style="border-left: 0;border-right: 0;">*</span>' +
        '<span class="input-group-addon" id="number-' + id + '">1</span>' +
        '<input class="hide" type="text" id="count-' + id + '" name="count"/> ' +
        '</div>' +
        '<div style="margin-bottom: 10px;">' +
        '<a href="javascript:addNode()" style="text-decoration: none"><span class="glyphicon glyphicon-plus-sign ion-content icon-add" aria-hidden="true">添加</span></a>' +
        '<a href="javascript:delNode(' + "'info-" + id + "'" + ')" style="text-decoration: none"> <span class="glyphicon glyphicon-minus-sign ion-content icon-dec" aria-hidden="true">删除</span></a>' +
        '</div></div>')
}

function delNode(val) {
    if ($('#info .input-group').length > 1) {
        $("#" + val).remove();
    } else {
        showAlert('商品大小必须存在，不能全部删除');
    }

}

function getValues() {
    var ue = UE.getEditor('editor');
    var text = ue.getContent();
}
